package com.ihrm.common.utils;

import com.google.gson.Gson;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class QiniuUploadUtil {
    
    private static final String accessKey = "COuoDRVa7JLsuurzIvQSI_pEDceHDw3yGfJEmvwv";
    private static final String secretKey = "3RWpTjB5Jxg3QosUFr4mxbHXJ5JR2m6AHQqYsSlr";
    private static final String bucket = "ihrm-bucket";
    private static final String prix = "http://pkbivgfrm.bkt.clouddn.com/";
    private UploadManager manager;
    
    public QiniuUploadUtil(){
        /**
         * 初始化基本配置
         */
        Configuration cfg = new Configuration(Zone.zone0());
    
        /**
         * 创建上传管理器
         */
        manager = new UploadManager(cfg);
    }
    
    public String upload(String imgName,byte[] bytes){
        Auth auth = Auth.create(accessKey, secretKey);
        /**
         * 构造覆盖上传token
         */
        String uploadToken = auth.uploadToken(bucket, imgName);
        try{
            Response response = manager.put(bytes, imgName, uploadToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            /**
             * 返回请求地址
             */
            String s = prix + putRet.key + "?t=" + (System.currentTimeMillis());
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
        
    }
}
